<?php
class MissionAction extends CommonAction {
	
	public function index(){
		$this->listorder = "id desc";
		$this -> listmap = "1 and site_id = ".$this->siteid;
		if(isset($_REQUEST['title'])){//任务标题
			if($_REQUEST['title']!==""){
				$this -> listmap .= " and title like '%{$_REQUEST[title]}%'";
			}
		}
		if(isset($_REQUEST['missionType'])){//任务类型
			if($_REQUEST['missionType']!==""){
				$this -> listmap .= " and missionType={$_REQUEST['missionType']}";
			}
		}
		if(isset($_REQUEST['state'])){//任务状态
			if($_REQUEST['state']!==""){
				$this -> listmap .= " and state={$_REQUEST['state']}";
			}
		}
		if(isset($_REQUEST['record'])){//流水号
			if($_REQUEST['record']!==""){
				$this -> listmap .= " and record={$_REQUEST['record']}";
			}
		}
			
		$this->_list();
		$list = $this->get('list');
		$scheduleDB = M('Schedule');
		$Users = M('user');
		foreach($list as $k => $v){
			//将当前任务的信息读取到数组中
			$list[$k]['schedule'] = $scheduleDB -> where(array('mission_id' => $v['id'])) ->order('datatime desc') -> find();
			//将当前进度处理人的信息读取到数组中
			$user = $Users -> where(array('id'=>$list[$k]['schedule']['user_id']))->find();
			$list[$k]['schedule']['user'] = $user;
		}
		
		$this->assign('list', $list);
		//echo $this->dao -> getLastSql();
		//dump($list);  //页面预览数据 便于操作
		$this->display();
			
	}
	
	//分页查询数据基方法
	public function _list($rename = '', $join = '', $field) {
        $map = $this->listmap;
        $order = $this->listorder;
        $pagesize = $this->pagesize;
        //计算总页数
        if ($join != '' || $rename != '') { //链接查询
            $count = $this->dao->alias($rename)->join($join)->where($map)->count();
            import('ORG.Util.Page');
            //实例化分页类
            $p = new Page($count, $pagesize);
            $this->list = $this->dao->alias($rename)->join($join)->where($map)->order($order)->Field($field)->group("m.id")->limit($p->firstRow . ',
	' . $p->listRows)->select();
            $this->pages = $p->show();
        } else {
            $count = $this->dao->where($map)->count();
            import('ORG.Util.Page');
            //实例化分页类
            $p = new Page($count, $pagesize);
            $this->list = $this->dao->where($map)->order($order)->limit($p->firstRow . ',
	' . $p->listRows)->select();
            $this->pages = $p->show();
        }
    }
	
	
	  
	  
	    //通用文件上传
    public function _upload($file = 'file') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile(); 
        //设置上传文件大小
        $upload->maxSize = 3*1024*1024;
        $upload->allowExts = explode(',', C('UPLOAD_EXTS'));
        $upload->savePath = "./Public/Uploads/".__SITEID__.'/'. MODULE_NAME . "" . __SITEID__ . "-";
        //自动命名
        $upload->saveRule = 'uniqid';
        //创建目录
        $upload->savePath = $upload->savePath . date('Ymd', time()) . "/";
        if (!file_exists("$upload->savePath")) {
            mk_dir($upload->savePath);
        }
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = 0;
        //设置需要生成缩略图的文件后缀
        //$upload->thumbSuffix = "_thumb";
        //设置缩略图最大宽度
        
        $upload->uploadReplace = true;
        if (!$upload->upload()) {
            $error = $upload->getErrorMsg();
            return $error;
        } else {
            $uploadList = $upload->getUploadFileInfo();
			return $uploadList;
        }
    }
	
	//添加内部任务 
	public function insert(){
		//echo session(C('USER_AUTH_KEY'));exit;
		
		 
		  $uploadret = $this->_upload();
		  $filekey = 0;
		  foreach($_FILES as $k => $v){
			  $_POST[$k] = $uploadret[$filekey]['savepath'].$uploadret[$filekey]['savename'];
			  $filekey++;
		  }
		  foreach($_POST as $k => $v){
			  if(is_array($v)){
				  $_POST[$k] = implode('　　',array_values($v));
			   }
		  }
		
		
		//实例化任务对象
		$_POST['missionType'] = 0;//内部任务
		$_POST['createtime'] = time();//提交时间
		$_POST['record'] = build_order_no();//流水号
		
		//发布者ID
		$promulgator = session(C('USER_AUTH_KEY'));
		$_POST['user_id'] = $promulgator;
		
		//当前表单ID
		$_POST['form_id'] = 10;
		
		$_POST['object'] = serialize($_POST);//所有表单数据 序列化到一个对象
		
		$_POST['state'] = 1;//内部任务默认属于 审核中
		
		M('mission')->add();
		
		//dump($_POST);
		//exit;
		parent::insert();
		 
		
	}
	
	//获取表单的模型信息   添加任务时所用的方法
	public function getForm(){
				  
		$fid = $this -> _post('fid');//获取表单表的ID值
		  
		//查询该表单的详细信息
		$Form = M('form');
		$res = $Form ->where(array('id'=>$fid)) ->find();
		$this -> assign('form',$res);
		$this -> assign('fid',$fid);
		
		$Field = M('field');
		$fields = $Field ->where(array('form_id' => $fid)) -> select();
		
		
		//遍历该表单下所有字段数据 将获得的数据做出处理渲染到表单模块 以达到页面获取表单模块的目的
		foreach($fields as $v){
			
			$this->assign('field_'.$v['id'],fieldDispose($v));
		}
		if(!$res){
			exit(json_encode(''));
		}
		//dump($res);exit;
		//取得表单的模块数据且渲染（ajax效果返回）
		$datas['temp'] = $this->fetch('',$res['template']);
		$datas['fid'] = $fid;
		echo json_encode($datas);
		//$this->ajaxReturn($this->fetch('',$res['template']));
	}
	
	public function add(){
		
		
		  //获取所有表单信息
		  $forms = M('form') -> select();
		  $this -> assign('forms',$forms);
		  $this->display();
			
	}
	
	//编辑页面
	public function edit(){
		$id = $this->_get('id');//获取任务表的ID
		$this->initView();
		$this->info = D('Mission') ->_getOne($this->view, $id);
		
		//dump($this->info);
		
		//dump($this->info);
		$this->display();
	}
	
	//查看页面
	public function find(){
		$id = $this->_get('id');//获取任务表的ID
		$datas = M('Mission') ->where(array('id'=>$id)) -> find();
		$mission = unserialize($datas['object']);
		
		//查询最新一条任务进度
		$sch = M('schedule');
		$schedule = $sch -> where(array('mission_id' => $id)) ->order('datatime desc') -> find();

		$this->assign($mission);//渲染任务数据到页面
		$this->assign('mission',$datas);//渲染任务数据到页面
		$this->assign('schedule',$schedule);//渲染进度数据到页面
		
		$Field = M('field');
		$fields = $Field ->where(array('form_id' => $datas['form_id'])) -> select();
		//遍历该表单下所有字段数据 将获得的数据做出处理渲染到表单模块 以达到页面获取表单模块的目的
		//dump($this->get('company'));
		foreach($fields as $v){
			if($v['f_type']==2){//如果该表单类型为2 即文本域 那么就改变渲染到页面的值
				$this->assign('field_'.$v['id'],'<a href="'.substr($this->get($v['f_name']),1,strlen($this->get($v['f_name']))).'">下载查阅</a>');
				continue;
			}
			
			//将字段名对应到表单中
			$this->assign('field_'.$v['id'],$this->get($v['f_name']));
		}
		
		//渲染表单数据到页面
		$form = M('Form') -> where(array('id' => $datas['form_id'])) -> find();
		$this->assign('res',$this->fetch('',$form['template']));
		$this->display();
	}
	
	//任务的更新操作 连带进度数据更新
	public function update(){
		$userID = session('authId');//当前登录用户ID
		//添加进度记录
		$scheduleDB = M('Schedule');
		$mid = $_POST['id'];
		$sch['mission_id'] = $mid;
		$sch['datatime'] = time();
		$sch['comment'] = $_POST['comment'];
		$sch['user_id'] = $userID;
		//$scheduleDB -> create($sch);
		$ret = $scheduleDB -> add($sch);
		
		//添加进度与用户的关联
		$scheduleUser = M('schedule_user');
		if($ret){
			$data['schedule_id'] = $ret;//任务进度ID
			$data['user_id'] = $userID;
			//$scheduleUser->create($data);
			$count = $scheduleUser->add($data);
		}
		
		if($ret){//如果有返回值 则进度添加成功 发送微信信息到关注此任务场景码的用户
			$MissionUser = M('Mission_user');
			//获取任务与用户关联表数据
			$missionUserDB = $MissionUser->where(array('mission_id'=>$mid))->find();
			$Mission = M('Mission');
			
			//更新状态
			//if(!$Mission -> create()){
				//$this->error($Mission -> getError());
			//}
			$ret = $Mission -> where(array('id' => $this -> _post('id'))) -> data($_POST) -> save();			
			//echo $Mission -> getLastSql();exit;
			//获取任务表数据
			$missionDB = $Mission->where(array('id'=>$mid))->find();
			//dump($missionDB);
			$state = $missionDB['state'];
			//echo '状态'.$state.'任务ID'.$mid;
			if($state==1){
				$state = '正在审核中';
			}else if($state==2){
				$state='正在处理中';
			}else if($state==3){
				$state='已完成';
			}
			$Member = M('member');
			//获取会员表数据
			//$memberDB = $Member->where(array('id'=>$missionUserDB['member_id']))->find();
			$wxuser = $Member -> where(array('id' => $missionDB['member_id'])) -> find(); 
			//dump($wxuser);exit;
			sendWXMsg($wxuser['openid'],"尊敬的".$wxuser['nickname']."，您好！\r\n您提交的项目：".$missionDB['title']."\r\nID为：".$missionDB['record']."\r\n目前状态：".$state."\r\n进度信息：".$sch['comment']."\r\n操作人：".getAdminName(session(C('USER_AUTH_KEY')))."\r\n<a href=\"".U('/Member/Mission/read',array('id' => $missionDB['id']),true,false,true)."\">查看详情</a>");
			//获取用户组数据
		    //parent::update();
			if($ret !== false){
			    $this->success('更新成功!', U('index'));
			}else{
				$this->success($Mission -> getError());
			}
		}
	} 
	
}